<script setup lang="ts">
import AppTable from "@/components/app/AppTable.vue";
import {listAllMenus, getRoleMenuIds, updateRoleMenus} from "@/api/system";
import {onMounted, ref} from "vue";
import type {IMenuVO} from "@/types";
import {ElMessage, ElTree} from "element-plus";

defineOptions({
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Role"
})

interface IRole {
  id: string
  label: string
  value: string
  permCount: number
}

const tableRef = ref()
const selectRoles = ref<IRole[]>([])
const menuList = ref<IMenuVO[]>([])
const menuDialogVisible = ref(false)
const currentRole = ref<IRole | null>(null)
const menuTreeRef = ref<InstanceType<typeof ElTree> | null>(null)
const checkedMenuIds = ref<number[]>([])

// 获取所有菜单列表
const loadMenuList = async () => {
  try {
    const res = await listAllMenus();
    menuList.value = res.data;
  } catch (error) {
    console.error("获取菜单列表失败:", error);
  }
};

// 打开菜单分配弹窗
const openMenuDialog = async (role: IRole) => {
  currentRole.value = role;
  menuDialogVisible.value = true;

  // 获取角色已分配的菜单（只获取实际拥有的菜单ID，不包含父节点）
  try {
    const res = await getRoleMenuIds(role.id);
    // 只使用实际拥有的菜单ID，让Element Plus自动处理父子节点状态
    checkedMenuIds.value = res.data || [];
  } catch (error) {
    console.error("获取角色菜单失败:", error);
    checkedMenuIds.value = [];
  }
};

// 保存菜单分配
const saveMenuAllocation = async () => {
  if (!currentRole.value) return;

  try {
    // 只获取完全选中的菜单ID，不包括父节点ID
    const checkedKeys = menuTreeRef.value?.getCheckedKeys(true) || [];
    let allCheckedKeys: number[] = checkedKeys as number[];

    console.log("选中的菜单ID:", allCheckedKeys)
    await updateRoleMenus(currentRole.value.id, allCheckedKeys);
    ElMessage.success("菜单分配成功");
    menuDialogVisible.value = false;

    // 刷新表格数据
    tableRef.value?.queryData();
  } catch (error: any) {
    ElMessage.error(error.msg || "菜单分配失败");
  }
};

// 关闭菜单分配弹窗
const closeMenuDialog = () => {
  menuDialogVisible.value = false;
  currentRole.value = null;
  checkedMenuIds.value = [];
};

onMounted(() => {
  loadMenuList();
})
</script>

<template>
  <div class="role-container">
    <AppTable
      ref="tableRef"
      title="角色管理"
      :search-info="[
      {
      label: '角色名称',
      key: 'roleName',
      value: ''
    }]"
      :btn-show="{
      add: false,
      edit: false,
      delete: false,
      export:false,
      import:false
    }"
      :pageable="false"
      api-method="get"
      api-path="/api/sys/role/query"
      @multiple-selection="data => {selectRoles = data}">
      <template v-slot:actionBar>
      </template>
      <template v-slot:tableColumn>
        <el-table-column prop="label" label="角色名称" align="left"/>
        <el-table-column label="权限字符" align="left">
          <template v-slot="scope">
            <el-tag type="success">{{ scope.row.value }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="接口权限个数" align="center">
          <template v-slot="scope">
            <div v-if="scope.row.value==='admin'" style="color: red">
              全系统权限
            </div>
            <div v-else>
              {{ scope.row.permCount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="scope">
            <el-button
              :disabled="scope.row.value==='admin'"
              type="primary"
              size="small"
              @click="openMenuDialog(scope.row)"
            >
              分配菜单
            </el-button>
          </template>
        </el-table-column>
      </template>
    </AppTable>

    <!-- 菜单分配弹窗 -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="`为角色【${currentRole?.label}】分配菜单`"
      width="600px"
      @close="closeMenuDialog"
    >
      <el-tree
        ref="menuTreeRef"
        :data="menuList"
        show-checkbox
        node-key="menuId"
        :default-checked-keys="checkedMenuIds"
        :props="{
          children: 'children',
          label: 'menuName'
        }"
        :default-expand-all="true"
        style="max-height: 400px; overflow-y: auto;"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeMenuDialog">取消</el-button>
          <el-button type="primary" @click="saveMenuAllocation">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
